<template>
  <div>
    <h1>{{id?'编辑':'新建'}}视频</h1>
    <el-form @submit.native.prevent="saveArticle" ref="form" :model="model" label-width="80px">
      <el-form-item label="上级分类">
        <el-select v-model="model.categories">
          <el-option
            v-for="item of videocategory"
            :key="item._id"
            :label="item.title"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="背景图">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :headers="getHeader()"
          :on-success="res=>$set(model,'bgImg',res.url)"
        >
          <img v-if="model.bgImg" :src="model.bgImg" class="banner" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="播放量">
        <el-input v-model="model.desc"></el-input>
      </el-form-item>
      <el-form-item label="视频地址">
        <el-input v-model="model.url"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {},
      parentOptions: [],
      pagedata:[],
      videocategory:[]
    };
  },
  created() {
    //this.feach()
    this.feachParentOptions();
    this.id && this.feach();
  },
  methods: {
    async feach() {
      const res = await this.$http.get(
        `rest/videos/${this.id}`
      ); /* .then(res=>{
          console.log(res.data);
          this.model=res.data
        }) */
      this.model = res.data;
    },
    onSubmit() {
      console.log("start!");
    },
    async saveArticle() {
      let res;
      if (this.id) {
        //编辑
        res = await this.$http.put(`rest/videos/${this.id}`, this.model);
      } else {
        //新建
        res = await this.$http.post("rest/videos", this.model);
      }
      this.$router.push("/videos/list");
      console.log(res.data);
      this.$message({
        message: "保存成功",
        type: "success"
      });
    },
    async feachParentOptions() {
      const res = await this.$http.get("rest/categories");
      this.parentOptions = res.data;
      this.parentOptions.forEach(ele => {
          if (!ele.parent) {
            this.pagedata.push(ele)
          }
        });
      this.pagedata.forEach(e => {
        e.children=[]
        for (const ele of this.parentOptions) {
          if (ele.parent) {
            if (ele.parent.title===e.title) {
              e.children.push(ele)
            }
          }
        }
      });
      this.videocategory=this.pagedata[2].children
    }
  }
};
</script>